<template>
	<div>
		<div class="gva-search-box">
			<el-form ref="searchForm" :inline="true" label-width="120" :model="searchInfo">
				<el-form-item label="废品名称">
					<el-input v-model="searchInfo.waste_name" placeholder="废品名称" />
				</el-form-item>
				<el-form-item label="时间">
					<el-date-picker v-model="data_select" type="datetimerange" start-placeholder="开始时间"
						end-placeholder="结束时间" unlink-panels value-format="YYYY-MM-DD HH:mm:ss" />
				</el-form-item>

				<el-form-item label="备注">
					<el-input v-model="searchInfo.notes" placeholder="备注" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
					<el-button icon="refresh" @click="onReset">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="gva-table-box">
			<div class="gva-btn-list">
				<el-button type="primary" icon="plus" @click="openDialog('addApi')">创建</el-button>
			</div>
			<el-table :data="tableData" row-key="id">
				<el-table-column align="left" label="资源ID" min-width="150" prop="waste_res_id" />
				<el-table-column align="left" label="废品名称" min-width="150" prop="waste_name" />
				<el-table-column align="left" label="废品唯一值" min-width="150" prop="unique_val" />
				<el-table-column align="left" label="用户价格" min-width="150" prop="waste_amount" />
				<el-table-column align="left" label="骑手价格" min-width="150" prop="rider_amount" />
				<el-table-column align="left" label="重量" min-width="150" prop="weight" />
				<el-table-column align="left" label="规格" min-width="150">
					<template #default="scope">
						<span>{{ displayState(scope.row.type) }}</span>
					</template>
				</el-table-column>
				<el-table-column align="left" label="审核状态" min-width="150">
					<template #default="scope">
						<span>{{ displayrole_type(scope.row.is_reviewer) }}</span>
					</template>
				</el-table-column>
				<el-table-column align="left" label="备注" min-width="150" prop="notes" />
				<!-- <el-table-column align="left" label="图片" min-width="200">
					<template #default="scope">
						<div style="display: flex;align-items: center;">
							<div v-for="(item,index) in scope.row.waste_imgs " >
								<img  :src="item.img" alt="Preview Image" style="width: 50px;height:50px" />
								
							</div>
							<el-button type="primary"  @click="syncChange(scope.row)" style="margin-left: 10px;">同步</el-button>
							
						</div>
					
					</template>
				</el-table-column> -->
				<el-table-column align="center" label="操作" min-width="200">
					<template #default="scope">
						<span @click="detailChange(scope.row)">详情</span>
						<span @click="fnChange(scope.row)" style="margin-left: 10px;">修改</span>
						<span style="color: #f00;margin-left: 10px;" @click="fnDelete(scope.row)">删除</span>
					</template>
				</el-table-column>
			</el-table>
			<div class="gva-pagination">
				<el-pagination :current-page="page" :page-size="page_size" :page-sizes="[10, 30, 50, 100]"
					:total="totals" layout="total, sizes, prev, pager, next, jumper"
					@current-change="handleCurrentChange" @size-change="handleSizeChange" />
			</div>
		</div>
		<el-drawer v-model="dialogFormVisible" size="60%" :before-close="closeDialog" :show-close="false">
			<template #header>
				<span class="text-lg">{{ isChange&&isDetail?"详情":isChange?"修改":"新增" }}</span>
				<div v-if="!isDetail">
					<el-button @click="closeDialog">取 消</el-button>
					<el-button type="primary" @click="enterDialog">确 定</el-button>
				</div>
			</template>
			<el-form ref="platForm" :model="form" :rules="rules" label-width="120px">
				<el-form-item label="废品名称" prop="waste_name">
					<el-input v-model="form.waste_name" placeholder="废品名称" :disabled="isDetail" />
				</el-form-item>
				<el-form-item label="废品唯一值" prop="unique_val">
					<el-input v-model="form.unique_val" placeholder="废品唯一值" :disabled="isDetail" />
				</el-form-item>
				<el-form-item label="用户价格" prop="waste_amount">
					<el-input v-model="form.waste_amount" placeholder="用户价格"
						oninput="value=value.replace(/[^0-9.]/g,'')" :disabled="isDetail" />
				</el-form-item>
				<el-form-item label="骑手价格" prop="rider_amount">
					<el-input v-model="form.rider_amount" placeholder="骑手价格"
						oninput="value=value.replace(/[^0-9.]/g,'')" :disabled="isDetail" />
				</el-form-item>
				<el-form-item label="重量" prop="weight">
					<el-input v-model="form.weight" placeholder="重量" oninput="value=value.replace(/[^0-9.]/g,'')"
						:disabled="isDetail" />
				</el-form-item>
				<el-form-item label="资源ID" prop="waste_res_id">
					<el-input v-model="form.waste_res_id" placeholder="资源ID" input="number" :disabled="isDetail" />
				</el-form-item>
				<el-form-item label="规格" prop="type">
					<el-select v-model="form.type" placeholder="请选择规格" :disabled="isDetail">
						<el-option v-for="item in stateOption" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="审核状态" prop="is_reviewer">
					<el-select v-model="form.is_reviewer" placeholder="请选择审核状态" :disabled="isDetail">
						<el-option v-for="item in statusOption" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="备注" prop="notes">
					<el-input v-model="form.notes" placeholder="备注" :disabled="isDetail" />
				</el-form-item>
				<!-- <el-form ref="uploadForm"  :model="form" :rules="rules" label-width="120px"> -->
				<el-form-item label="图片上传" prop="waste_imgs" class="upload">
					<!-- :show-file-list="false" -->
					<div v-if="!isDetail">
						<el-upload action="/api/fileUploadAndDownload/upload" list-type="picture-card"
							:on-success="handleSuccess" :on-remove="handleRemove" :before-remove="beforeRemove"
							:on-preview="handlePictureCardPreview" :before-upload="BeforeLoad"
							:file-list="form.waste_imgs" :multiple="false">
							<div class="upload-btn">
								<el-icon class="avatar-uploader-icon">
									<Plus />
								</el-icon>
							</div>
						</el-upload>
					</div>
					<div v-else>
						<div style="display: flex;align-items: center;">
							<div v-for="(item,index) in form.waste_imgs ">
								<img :src="item.img" alt="Preview Image" style="width:100px;height:100px" />

							</div>

						</div>
						<el-button type="primary" @click="syncChange()" style="margin-left: 10px;">同步</el-button>

					</div>


					<el-dialog v-model="dialogVisible">
						<img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%" />
					</el-dialog>
				</el-form-item>
				<!-- </el-form> -->
			</el-form>
		</el-drawer>
	</div>
</template>
<script setup>
	defineOptions({
		name: "wasteTypeIndex"
	});
	import {
		isImageMime
	} from "@/utils/image";

	import {
		ref,
		onMounted,
		computed
	} from "vue";

	import {
		waste_typeList,
		waste_typeAdd,
		waste_typeUpdate,
		waste_typeDelete,
		waste_Image
	} from "@/api/subscribe";
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";
	let searchInfo = ref({

		waste_name: "",
		type: null,
		notes: "",
		unique_val: "",
		waste_amount: null,
		rider_amount: null,
		weight: "",
		waste_res_id: "",
		is_reviewer: null,
		s_at: "",
		e_at: ""
	});
	let tableData = ref([
		// {
		//   id: 1,
		//   waste_name: "1",
		//   type: "1",
		//   notes: "1",
		//   unique_val: "1",
		//   waste_amount: "1",
		//   rider_amount: "1",
		//   weight: "1",
		//   waste_res_id: "1",
		//   is_reviewer: "1"
		// }
	]);
	let totals = ref(0);
	let page = ref(1);
	let page_size = ref(10);
	let data_select = ref(""); // 时间
	const indexRemove = ref();
	const dialogImageUrl = ref('');
	const dialogVisible = ref(false);
	const stateOption = [{
			id: 1,
			name: "每/公斤"
		},
		{
			id: 2,
			name: "每个"
		}
	];
	const statusOption = [{
		id: 1,
		name: "已审核"
	}];
	let form = ref({
		waste_name: "",
		type: null,
		notes: "",
		unique_val: "",
		waste_amount: null,
		rider_amount: null,
		weight: "",
		waste_res_id: "",
		is_reviewer: "",
		waste_imgs: []
	});
	const rules = ref({
		waste_imgs: [{
			required: true,
			message: "请上传图片",
			trigger: "blur"
		}],

		// waste_name: [{ required: true, message: "请输入废品名称", trigger: "blur" }],
		// notes: [{ required: true, message: "请输入备注", trigger: "blur" }],
		// type: [{ required: true, message: "请选择规格", trigger: "blur" }],
		// unique_val: [
		//   { required: true, message: "请输入废品唯一值", trigger: "blur" }
		// ],
		// waste_amount: [
		//   { required: true, message: "请输入用户价格", trigger: "blur" }
		// ],
		// rider_amount: [
		//   { required: true, message: "请输入骑手价格", trigger: "blur" }
		// ],
		// weight: [{ required: true, message: "请输入重量", trigger: "blur" }],
		// waste_res_id: [{ required: true, message: "请输入资源ID", trigger: "blur" }],
		// is_reviewer: [{ required: true, message: "请选择审核状态", trigger: "blur" }]
	});
	let dialogFormVisible = ref(false);
	const platForm = ref();
	let isChange = ref(false);
	let isDetail = ref(false);
	onMounted(() => {
		getList();
	});

	const displayrole_type = computed(() => {
		return val => {
			if (val === "1") {
				return "审核通过";
			} else {
				return "-";
			}
		};
	});
	const displayState = computed(() => {
		return val => {
			console.log(val);
			if (val === "1") {
				return "每/公斤";
			} else if (val === "2") {
				return "每个";
			} else {
				return "-";
			}
		};
	});
	const enterDialog = () => {
		console.log(form.value)
		form.value.waste_amount = parseFloat(form.value.waste_amount);
		form.value.rider_amount = parseFloat(form.value.rider_amount);
		form.value.weight = parseFloat(form.value.weight);
		form.value.waste_res_id = parseFloat(form.value.waste_res_id);
		let params = form.value;

		platForm.value.validate(async valid => {
			if (valid) {
				if (!isChange.value) {
					waste_typeAdd(params).then(response => {
						if (response.code === 200) {
							ElMessage({
								message: response.msg || "新增成功",
								type: "success"
							});
							closeDialog();
							page.value = 1;
							page_size.value = 10;
							getList();
						}
					});
				} else {
					waste_typeUpdate(params).then(response => {
						if (response.code === 200) {
							ElMessage({
								message: response.msg || "修改成功",
								type: "success"
							});
							closeDialog();
							page.value = 1;
							page_size.value = 10;
							getList();
						}
					});
				}
			}
		});
	};
	const openDialog = () => {
		isDetail.value=false
		isChange.value = false
		dialogFormVisible.value = true;
	};
	const closeDialog = () => {
		form.value = {
			name: ""
		};
		platForm.value.resetFields();
		dialogFormVisible.value = false;
	};
	const fnDelete = row => {
		ElMessageBox.confirm("是否删除该条数据", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			})
			.then(async () => {
				let params = {
					id: row.id
				};
				const response = await waste_typeDelete(params);
				if (response.code === 0) {
					ElMessage({
						type: "success",
						message: "删除成功!"
					});
					getList();
				}
			})
			.catch(() => {
				ElMessage({
					type: "info",
					message: "已取消删除"
				});
			});
	};
	const syncChange = () => {
		let params = {
			waste_img_ids: ""
		}
    console.log(params.waste_img_ids)
		form.value.waste_imgs.forEach(item => {
			params.waste_img_ids += item.id + ","
		})
		  console.log(params.waste_img_ids)
		params.waste_img_ids = params.waste_img_ids.slice(0, params.waste_img_ids.length - 1)
		waste_Image(params).then(response => {
			if (response.code === 200) {
				tableData.value = response.data.rows || [];
				totals.value = response.data.total_rows || 0;
			}
		});

		dialogFormVisible.value = true;
	};
	const detailChange = row => {
		isChange.value = true;
		isDetail.value = true;
		form.value = JSON.parse(JSON.stringify(row));
		console.log(form.value);
		form.value.waste_imgs.forEach(item => {
			item.url = item.img
		})
		dialogFormVisible.value = true;
	};
	const fnChange = row => {
		isChange.value = true;
		isDetail.value = false;
		form.value = JSON.parse(JSON.stringify(row));
		console.log(form.value);
		form.value.waste_imgs.forEach(item => {
			item.url = item.img
		})
		dialogFormVisible.value = true;
	};
	const getList = () => {
		let params = {
			page: page.value,
			page_size: page_size.value,
			waste_name: searchInfo.value.waste_name,
			type: searchInfo.value.type,
			notes: searchInfo.value.notes,
			unique_val: searchInfo.value.unique_val,
			waste_amount: searchInfo.value.waste_amount,
			rider_amount: searchInfo.value.rider_amount,
			weight: searchInfo.value.weight,
			waste_res_id: searchInfo.value.waste_res_id,
			is_reviewer: searchInfo.value.is_reviewer,
			e_at: searchInfo.value.e_at,
			s_at: searchInfo.value.s_at
		};
		waste_typeList(params).then(response => {
			if (response.code === 200) {
				tableData.value = response.data.rows || [];
				totals.value = response.data.total_rows || 0;
			}
		});
	};
	const handleCurrentChange = val => {
		page.value = val;
		getList();
	};
	const handleSizeChange = val => {
		page_size.value = val;
		getList();
	};
	const onSubmit = () => {
		page.value = 1;
		page_size.value = 10;
		if (data_select.value) {
			searchInfo.value.s_at = data_select.value[0];
			searchInfo.value.e_at = data_select.value[1];
		}

		getList();
	};
	const onReset = () => {
		searchInfo.value = {
			waste_name: "",
			type: null,
			notes: "",
			unique_val: "",
			waste_amount: null,
			rider_amount: "",
			weight: "",
			waste_res_id: "",
			is_reviewer: "",
			s_at: "",
			e_at: ""

		};
		page.value = 1;
		page_size.value = 10;
		totals.value = 0;
		getList();
	};
	const BeforeLoad = file => {
		if (file.size > 5 * 1024 * 1024) {
			ElMessage({
				message: "当前文件大于5M，请重新选择",
				type: "error"
			});
			return;
		} else {
			const isImage = isImageMime(file.type);
			let pass = true;
			if (!isImage) {
				ElMessage.error("只能上传 jpg,png,svg,webp 格式的图片!");
				pass = false;
			}
			return pass;
		}
	};

	// 预览
	const handlePictureCardPreview = (uploadFile) => {
		dialogImageUrl.value = uploadFile.img
		dialogVisible.value = true
	};
	const beforeRemove = (file, fileList) => {
		indexRemove.value = fileList.findIndex((files) => files.url == file.url)
		return true
	};
	//移除文件
	const handleRemove = (file, fileList) => {
		form.value.waste_imgs.splice(indexRemove.value, 1)
	};
	const handleSuccess = (response, file, fileList) => {
		// 这里可以根据你的后端返回的数据结构来调整，以下是一个示例：
		form.value.waste_imgs.push({
			"img": response.data.file.url,
			"url": response.data.file.url
		});

	};
</script>
<style lang="scss" scoped>
	.avatar {
		width: 60px;
		height: 60px;
		margin-right: 10px;
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 100px;
		height: 100px;
		text-align: center;
		border: 1px solid #f6f2f3;
	}

	.el-icon.avatar-uploader-icon:hover {
		box-shadow: 0 0 2px 4px rgba(246, 242, 243, 0.3);
	}

	.img-box:hover {
		box-shadow: 0 0 2px 4px rgba(246, 242, 243, 0.3);
	}

	.img-box {
		width: 100px;
		height: 100px;
		border: 1px solid #f6f2f3;
		padding: 4px;
		border-radius: 4px;
		box-sizing: border-box;
		margin-right: 10px;

		.img {
			width: 100%;
			height: 100%;
			object-fit: contain;
		}
	}

	.upload {
		.el-form-item {
			width: 100px;
		}
	}
</style>
